package com.nerve.cloudoffice.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.nerve.cloudoffice.domain.Department;
import com.nerve.cloudoffice.domain.bean.DepartmentTask;
import com.nerve.cloudoffice.domain.dao.DepartmentDao;
import com.nerve.cloudoffice.domain.dao.TaskDao;
import com.nerve.cloudoffice.service.DepartmentService;

/**
 * @project cloudOffice DepartmentServiceImpl.java
 * @datetime Jul 30, 2013 4:18:56 AM
 * @description 
 *    
 * @author 集成显卡 IBM 
 *			zxingming@qq.com
 *			zengxm@cn.ibm.com
 *
 * @change log:
 *
 */
public class DepartmentServiceImpl implements DepartmentService{
	
	private DepartmentDao dao;
	private TaskDao taskDao;
	
	private TaskDao getTaskDao(){
		if(taskDao == null)
			taskDao = new TaskDao();
		
		return taskDao;
	}
	
	public int delete(int id) throws Exception {
		getDao().delete(id);
		return 0;
	}

	public List<Department> listAll() {
		return getDao().getList();
	}

	public int save(Department department) throws Exception {
		if(department.getId() > 0){
			getDao().update(department);
		}
		else{
			getDao().save(department);
		}
		return department.getId();
	}

	public DepartmentDao getDao(){
		if(dao == null)
			dao = new DepartmentDao();
		
		return dao;
	}

	public List<DepartmentTask> countTask() throws Exception {
		List<DepartmentTask> dtList = new ArrayList<DepartmentTask>();
		
		List<Department> dl = getDao().getList();
		for(Department d:dl){
			DepartmentTask dt = new DepartmentTask();
			dt.setId(d.getId());
			dt.setName(d.getName());
			
			dt.setTaskCount(countUndoTask(d.getId()));
			
			dtList.add(dt);
		}
		
		return dtList;
	}
	
	public int countUndoTask(int did){
		String hql = "FROM Task as t WHERE t.status<100 and t.workUser.department.id=" + did;
		
		return getTaskDao().countRow(hql);
	}
}